import Cookies from 'js-cookie'
import axios from 'axios'
import Message from '@/utils/message'
import store from '@/store'
import { TokenType } from '@/utils/enum'

// create an axios instance
const baseURL = process.env.VUE_APP_BASE_API
const service = axios.create({
  baseURL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30 * 1000 ,// request timeout
})
// request interceptor
service.interceptors.request.use(
  async config => {
    console.log('config:')
    console.log(config)
    if (config.url === '/oauth/token') {
      return config
    }
    var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJncmFudF90eXBlIjoiY2xpZW50X2NyZWRlbnRpYWxzIiwic2NvcGUiOlsiYXJjaGl2ZXNfYWRtaW4iXSwiY2xpZW50X2lkIjoia2FuY2hhX2FkbWluIn0.m4W7wV9c8CgNFIIan5sR-xsUqiy3t41bKyISIkqnIbs';
    config.headers['Authorization'] = 'Bearer ' + token
    return config
  },
  error => {
    // do something with request error
    console.log('请求错误原因：' + error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor

service.interceptors.response.use(function(response) {
  console.log("response", response)
  if (response.status === 200) {
    if(response.data.error_message) {
      _message(response.data.error_message)
      return false
    } else {
      return response.data || true
    }
  }
  return response

},function(error) {
  console.log("error",error.response)
  if(!error.response) {
    _message("网络请求异常")
    return;
  }
  if (error.response.config.url.indexOf("/oauth/token") >= 0) {
    _message("登陆异常")
    return;
  }
  switch (error.response.status) {
    case 400:
      _message("请求错误")
      break
    case 401:
      _message('请重新登录')
      break
    case 403:
      _message('权限不足')
      return
    case 500:
      _message('系统繁忙,请稍候再试');
      break
    default:
      _message('请求异常');
      break
  }
})

function _message(msg) {
  Message({
    message: msg,
    type: 'error',
    duration: 2000
  })
}
export default service
